<?php

namespace app\rongcui\controller;

use app\rongcui\model\RongcuiIndustryTypeModel;
use app\rongcui\model\AreasModel;
use app\rongcui\model\RongcuiFollowModel;
use app\rongcui\model\RongcuiBuyerUserModel;
use app\rongcui\model\CustomerNatureModel;
use app\rongcui\model\RongcuiIndustryCateModel;
use app\rongcui\model\RongcuiBuyerModel;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;

class BuyerController extends AdminBaseController
{
    private $cate;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 买家列表
     * @adminMenu(
     *     'name'   => '买家列表',
     *     'parent' => 'business/LicensePlate/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '买家列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $where = [
            'lock_uid' => 0
        ];
        if (input('source')) {
            $where['buyer.source'] = input('source');
        }
        if (input('nature')) {
            $where['buyer.nature'] = input('nature');
        }
        if (input('is_done')) {
            $where['buyer.is_done'] = input('is_done', 0, 'intval') - 1;
        }
        if (input('start_time')) {
            $where['buyer.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d', $endtime));
            if ($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['buyer.createtime'])) {
                $where['buyer.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['buyer.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['buyer.name|buyer.phone|buyer.remark|user.user_nickname|userb.user_nickname'] = ['like', "%$keyword%"];
        }

        $admin_id = cmf_get_current_admin_id();
        $cata_where = [];
        if($admin_id !=  1) {

            $roles = db('role_user')
                ->where(['user_id' => $admin_id])
                ->column('role_id');

            $role_deps = get_show_department($roles);
            $flag = true;
            foreach ($role_deps as $role_dep) {
                if($role_dep['company_manage']) {
                    $flag = false;
                }
            }

            if($flag) {
                $items = db('role_user')
                    ->alias('role_user')
                    ->join('__ROLE_ITEM__ role_item','role_user.role_id = role_item.role_id and role_item.config_id = 3')
                    ->where([
                        'role_user.user_id' => $admin_id
                    ])
                    ->field('item_id')
                    ->select();
                $item_val = [0];
                foreach ($items as $item) {
                    $item_val[] = $item['item_id'];
                }
                $cata_where['show_id'] = ['in',$item_val];
            }
        }
        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel
            ->where($cata_where)
            ->where([
                'is_del' => 0
            ])->order('parent_id,list_order,id')->select();

        $cids = [];
        foreach ($cate as $cat) {
            $cids[] = $cat['id'];
        }
        $where['ctype.cate_id'] = ['in',$cids];
        if(input('category')) {
            $where['ctype.cate_id'] = input('category');
        }


        $buyerModel = new RongcuiBuyerModel();
        $lists = $buyerModel
            ->alias('buyer')
            ->join('__RONGCUI_INDUSTRY_TYPE__ ctype', 'buyer.id = ctype.pid')
            ->join('__CUSTOMER_NATURE__ nature', 'buyer.nature = nature.id','left')
            ->join('__RONGCUI_FOLLOW__ follow','buyer.id = follow.pid and follow.type = 2','left')
            ->join('__RONGCUI_BUYER_USER__ buser','buyer.id = buser.pid and buser.level = 1')
            ->join('__USER__ user','user.id = follow.uid','left')
            ->join('__USER__ userb','userb.id = buser.uid')
            ->group('buyer.id')
            ->where('char_length(buyer.name) <= 8')
            ->where($where)
            ->field([
                'buyer.*',
                'nature.name nname,userb.user_nickname uname'
            ])
            ->order('buyer.createtime desc,buyer.id desc')
            ->paginate();


        $customerNatureModel = new CustomerNatureModel();
        $source = $customerNatureModel->where([
            'type' => 2,
            'is_del' => 0
        ])->field('id,name')->select();

        $nature = $customerNatureModel->where([
            'type' => 8,
            'is_del' => 0
        ])->field('id,name')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('source', $source);
        $this->assign('nature', $nature);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        if ($this->request->isPost()) {
            $this->addPost(1);
        }
        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();


        $admin_id = cmf_get_current_admin_id();
        $cata_where = [];
        if($admin_id !=  1) {

            $roles = db('role_user')
                ->where(['user_id' => $admin_id])
                ->column('role_id');

            $role_deps = get_show_department($roles);
            $flag = true;
            foreach ($role_deps as $role_dep) {
                if($role_dep['company_manage']) {
                    $flag = false;
                }
            }

            if($flag) {
                $items = db('role_user')
                    ->alias('role_user')
                    ->join('__ROLE_ITEM__ role_item','role_user.role_id = role_item.role_id and role_item.config_id = 3')
                    ->where([
                        'role_user.user_id' => $admin_id
                    ])
                    ->field('item_id')
                    ->select();
                $item_val = [0];
                foreach ($items as $item) {
                    $item_val[] = $item['item_id'];
                }
                $cata_where['show_id'] = ['in',$item_val];
            }
        }
        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel
            ->where($cata_where)
            ->where([
                'status' => 1,
                'is_del' => 0
            ])->order('parent_id,list_order,id')->select();

        $this->assign('areaslist', $areaslist);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    function add_lock()
    {
        if ($this->request->isPost()) {
            $this->addPost(2);
        }
        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $admin_id = cmf_get_current_admin_id();
        $cata_where = [];
        if($admin_id !=  1) {

            $roles = db('role_user')
                ->where(['user_id' => $admin_id])
                ->column('role_id');

            $role_deps = get_show_department($roles);
            $flag = true;
            foreach ($role_deps as $role_dep) {
                if($role_dep['company_manage']) {
                    $flag = false;
                }
            }

            if($flag) {
                $items = db('role_user')
                    ->alias('role_user')
                    ->join('__ROLE_ITEM__ role_item','role_user.role_id = role_item.role_id and role_item.config_id = 3')
                    ->where([
                        'role_user.user_id' => $admin_id
                    ])
                    ->field('item_id')
                    ->select();
                $item_val = [0];
                foreach ($items as $item) {
                    $item_val[] = $item['item_id'];
                }
                $cata_where['show_id'] = ['in',$item_val];
            }
        }
        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel
            ->where($cata_where)
            ->where([
                'status' => 1,
                'is_del' => 0
            ])->order('parent_id,list_order,id')->select();


        $this->assign('areaslist', $areaslist);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    protected function addPost($type)
    {
        $buyerModel = new RongcuiBuyerModel();
        $arrData = $this->request->post();
        if(!isset($arrData['manager'])) {
            $arrData['manager'] = cmf_get_current_admin_id();
        }
        if($type == 2) {
            $arrData['lock_uid'] = cmf_get_current_admin_id();
            $arrData['data_type'] = 1;
            $arrData['lock_time'] = time();
        }

        $arrData['createtime'] = strtotime($arrData['createtime']);
        if (!$arrData['createtime']) {
            $arrData['createtime'] = time();
        }
        $cids = explode(',', $arrData['cid']);
        if (!$cids) {
            $this->error('行业类别不能为空');
        }
        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel->find($arrData['cid']);
        $arrData['cname'] = $cate['name'];

        $result = $buyerModel->allowField(true)->validate('rongcui/RongcuiBuyer')->save($arrData);
        if ($result) {
            $data = [];
            foreach ($cids as $cid) {
                $data[] = [
                    'pid' => $buyerModel->id,
                    'cate_id' => $cid,
                    'level' => 1
                ];
            }

            $rongcuiIndustryTypeModel = new RongcuiIndustryTypeModel();
            $rongcuiIndustryTypeModel->allowField(true)->saveAll($data);
            $buyerUserModel = new RongcuiBuyerUserModel();
            $buyerUserModel->allowField(true)->saveAll([
                ['pid' => $buyerModel->id, 'uid' => cmf_get_current_admin_id(), 'level' => 1],
                ['pid' => $buyerModel->id, 'uid' => $arrData['manager'], 'level' => 2],
            ]);
            if($type == 2) {
                $this->success(lang("ADD_SUCCESS"), url("lock_lists"));
            }
            $this->success(lang("ADD_SUCCESS"), url("index"));
        } else {
            $this->error($buyerModel->getError());
        }
    }

    /**
     * 编辑买家
     * @adminMenu(
     *     'name'   => '编辑买家',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家',
     *     'param'  => ''
     * )
     */
    function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        $buyerModel = new RongcuiBuyerModel();
        $result = $buyerModel
            ->alias('buyer')
            ->join('__USER__ user', 'buyer.manager = user.id', 'left')
            ->join('__CUSTOMER_NATURE__ nature', 'buyer.source = nature.id and nature.type = 2', 'left')
            ->join('__CUSTOMER_NATURE__ nature_level', 'buyer.customer_level = nature_level.id and nature_level.type = 3', 'left')
            ->join('__CUSTOMER_NATURE__ ntru', 'buyer.nature = ntru.id and ntru.type = 8', 'left')
            ->field([
                'buyer.*',
                'user.user_nickname as mname',
                'nature.name as nname',
                'nature_level.name as level_name',
                'ntru.name as nature_name'
            ])
            ->where(['buyer.id' => $id])->find();

        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel->where([
            'status' => 1,
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $this->assign('areaslist', $areaslist);
        $this->assign('result', $result);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    /**
     * 编辑买家提交
     * @adminMenu(
     *     'name'   => '编辑买家提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家提交',
     *     'param'  => ''
     * )
     */
    function editPost()
    {
        $buyerModel = new RongcuiBuyerModel();
        $arrData = $this->request->post();
        if(!isset($arrData['manager'])) {
            $arrData['manager'] = cmf_get_current_admin_id();
        }

        if(isset($arrData['createtime'])) {
            $arrData['createtime'] = strtotime($arrData['createtime']);
            if (!$arrData['createtime']) {
                $arrData['createtime'] = time();
            }
        }else{
            $arrData['createtime'] = time();
        }

        if(isset($arrData['cid'])) {
            $cids = explode(',', $arrData['cid']);
            if (!$cids) {
                $this->error('行业类别不能为空');
            }
            $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
            $cate = $rongcuiIndustryCateModel->find($arrData['cid']);
            $arrData['cname'] = $cate['name'];
            $data = [];
            foreach ($cids as $cid) {
                $data[] = [
                    'pid' => $arrData["id"],
                    'cate_id' => $cid,
                    'level' => 1
                ];
            }
        }

        $result = $buyerModel->allowField(true)->validate(true)->save($arrData, ["id" => $arrData["id"]]);
        if ($result !== false) {
            if(isset($data)) {
                $rongcuiIndustryTypeModel = new RongcuiIndustryTypeModel();
                $rongcuiIndustryTypeModel->where(['pid' => $arrData['id'], 'level' => 1])->delete();
                $rongcuiIndustryTypeModel->allowField(true)->saveAll($data);
            }

            $buyerUserModel = new RongcuiBuyerUserModel();
            $buyerUserModel->allowField(true)->save(['uid' => $arrData['manager']], ['pid' => $buyerModel->id, 'level' => 2]);

            $this->success(lang("EDIT_SUCCESS"), url("Buyer/lock_lists"));
        } else {
            $this->error($buyerModel->getError());
        }
    }

    /**
     * 买家跟进
     * @adminMenu(
     *     'name'   => '买家跟进',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '买家跟进',
     *     'param'  => ''
     * )
     */
    function follow()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if (!$pid) {
            $this->error('非法访问');
        }
        $followModel = new RongcuiFollowModel();
        $where = ['type' => 2, 'pid' => $pid];
        $lists = $followModel
            ->alias('follow')
            ->join('__USER__ user','follow.uid = user.id')
            ->field('follow.*,user.user_nickname')
            ->where($where)
            ->order(['id desc'])
            ->paginate(10);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 买家跟进
     * @adminMenu(
     *     'name'   => '买家跟进',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '买家跟进',
     *     'param'  => ''
     * )
     */
    function show()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if (!$pid) {
            $this->error('非法访问');
        }
        $followModel = new RongcuiFollowModel();
        $where = ['type' => 2, 'pid' => $pid];
        $lists = $followModel
            ->alias('follow')
            ->join('__USER__ user','follow.uid = user.id')
            ->field('follow.*,user.user_nickname')
            ->where($where)
            ->order(['id desc'])
            ->paginate(10);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 添加买家跟进
     * @adminMenu(
     *     'name'   => '添加买家跟进',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加买家跟进',
     *     'param'  => ''
     * )
     */
    function add_follow()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if (!$pid) {
            $this->error('非法访问');
        }

        $rongcuiBuyerModel = new RongcuiBuyerModel();
        $result = $rongcuiBuyerModel->find($pid);

        $customerNatureModel = new CustomerNatureModel();
        $lists = $customerNatureModel->where([
            'type' => 8
        ])->order('list_order,id')->select();

        $this->assign('result', $result);
        $this->assign('lists', $lists);
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 添加买家跟进提交
     * @adminMenu(
     *     'name'   => '添加买家跟进提交',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加买家跟进提交',
     *     'param'  => ''
     * )
     */
    function add_followPost()
    {
        $followModel = new RongcuiFollowModel();
        $arrData = $this->request->post();

        $time = time();
        $arrData['create_time'] = $time;
        $arrData['type'] = 2;
        $arrData['uid'] = cmf_get_current_admin_id();
        $arrData['next_time'] = strtotime($arrData['next_time']);
        if ($arrData['next_time'] < $time) {
            $arrData['next_time'] = 0;
        }
        if (!$arrData['pid']) {
            $this->error('非法访问');
        }

        $result = $this->validate($arrData, 'Follow');
        if ($result !== true) {
            $this->error($result);
        }

        $result = $followModel->allowField(true)->save($arrData);
        if ($result) {
            $resData = [
                'evolve' => $arrData['remark'],
                'newtime' => $time,
                'nexttime' => $arrData['next_time']
            ];
            if(isset($arrData['nature'])) {
                $resData['nature'] = $arrData['nature'];
            }
            $buyerModel = new RongcuiBuyerModel();
            $buyerModel->where(['id' => $arrData['pid']])->update($resData);
        }

        $this->success(lang("ADD_SUCCESS"), url("follow", ['pid' => $arrData['pid']]));
    }

    /**
     * 编辑买家跟进
     * @adminMenu(
     *     'name'   => '编辑买家跟进',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家跟进',
     *     'param'  => ''
     * )
     */
    function edit_follow()
    {
        $id = $this->request->param('id', 0, 'intval');
        $followModel = new RongcuiFollowModel();
        $result = $followModel->where(['id' => $id])->find();


        $rongcuiBuyerModel = new RongcuiBuyerModel();
        $info = $rongcuiBuyerModel->find($result['pid']);

        $customerNatureModel = new CustomerNatureModel();
        $lists = $customerNatureModel->where([
            'type' => 8
        ])->order('list_order,id')->select();

        $this->assign('result', $result);
        $this->assign('lists', $lists);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 编辑买家跟进提交
     * @adminMenu(
     *     'name'   => '编辑买家跟进提交',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家跟进提交',
     *     'param'  => ''
     * )
     */
    function edit_followPost()
    {
        $followModel = new RongcuiFollowModel();
        $arrData = $this->request->post();

        $time = time();
        $arrData['next_time'] = strtotime($arrData['next_time']);
        if ($arrData['next_time'] < $time) {
            $arrData['next_time'] = 0;
        }

        $result = $this->validate($arrData, 'Follow.edit');
        if ($result !== true) {
            $this->error($result);
        }

        $result = $followModel->allowField(true)->save($arrData,["id" => $arrData["id"]]);
        if ($result !== false) {
            $new = $followModel->where(['type' => 2, 'pid' => $arrData['pid']])->max('id');
            if ($new == $arrData['id']) {
                $resData = [
                    'evolve' => $arrData['remark'],
                    'newtime' => $time,
                    'nexttime' => $arrData['next_time']
                ];
                if(isset($arrData['nature'])) {
                    $resData['nature'] = $arrData['nature'];
                }
                $buyerModel = new RongcuiBuyerModel();
                $buyerModel->where(['id' => $arrData['pid']])->update($resData);
            }
        }

        $this->success(lang("EDIT_SUCCESS"), url("follow", ['pid' => $arrData['pid']]));
    }

    function done()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误');
        }

        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['lock_uid'] = ['in', $users];
        }
        $where['buyer.id'] = $id;

        $buyerModel = new RongcuiBuyerModel();
        $buyer = $buyerModel
            ->alias('buyer')
            ->where($where)
            ->field([
                'buyer.id',
            ])
            ->find();
        if (!$buyer) {
            $this->error('非法操作');
        }

        $buyerModel->save([
            'done_sq' => 1
        ], ['id' => $id]);
        $this->success('处理完成');
    }

    function notdone()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误');
        }

        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['lock_uid'] = ['in', $users];
        }
        $where['buyer.id'] = $id;

        $buyerModel = new RongcuiBuyerModel();
        $buyer = $buyerModel
            ->alias('buyer')
//            ->join('__BUYER_USER__ cbuser', 'buyer.id = cbuser.pid and cbuser.level = 1', 'left')//创建
//            ->join('__BUYER_USER__ mbuser', 'buyer.id = mbuser.pid and mbuser.level = 2', 'left')//负责
//            ->join('__BUYER_USER__ sbuser', 'buyer.id = sbuser.pid and sbuser.level = 3', 'left')//分享

//            ->join('__USER__ cuser', 'cbuser.uid = cuser.id')
//            ->join('__USER__ muser', 'mbuser.uid = muser.id')
            ->where($where)
            ->field([
                'buyer.id',
            ])
            ->find();
        if (!$buyer) {
            $this->error('非法操作');
        }

        $buyerModel->save([
            'is_done' => 0
        ], ['id' => $id]);
        $this->success('处理完成');
    }

    /**
     * 记录分配
     * @adminMenu(
     *     'name'   => '记录分配',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分配',
     *     'param'  => ''
     * )
     */
    function allot()
    {
        $check_ids = $this->request->param('check_ids', '');
        $buyerUserModel = new RongcuiBuyerUserModel();
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids', 0, 'intval');
            $buyerUserModel->allowField(true)->save(['uid' => $ids], [
                'pid' => ['in', $check_ids],
                'level' => 2
            ]);
            $buyerModel = new RongcuiBuyerModel();
            $buyerModel->save([
                'manager' => $ids
            ], [
                'id' => ['in', $check_ids],
            ]);
            $this->success('设置成功');
        } else {
            $userModel = new UserModel();

            $where = [];
            $uid = cmf_get_current_admin_id();
            $flag = false;
            if ($uid != 1) {
                $roles = db('role_user')
                    ->where(['user_id' => $uid])
                    ->column('role_id');

                $role_deps = get_role_department($roles, 'data_to_all_user');
                foreach ($role_deps as $role_dep) {
                    if ($role_dep['data_to_all_user']) {
                        $flag = true;
                    }
                }
            }

            if ($uid != 1 && !$flag) {
                $where['dep.id'] = ['in', getUsersGroup($uid)];
            }
            $where['user_status'] = ['neq', 0];

            $lists = $userModel
                ->alias('user')
                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
                ->field([
                    'user.*',
                    'dep.name as dep_name,dep.id as dep_id'
                ])->where($where)->select();

            $users = $buyerUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 2
            ])->column('uid');

            $this->assign('lists', $lists);
            $this->assign('users', $users);
            return $this->fetch();
        }
    }

    /**
     * 记录分享
     * @adminMenu(
     *     'name'   => '记录分享',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分享',
     *     'param'  => ''
     * )
     */
    function share()
    {
        $check_ids = $this->request->param('check_ids', '');
        $buyerUserModel = new RongcuiBuyerUserModel();
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids', '');
            $users = $buyerUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 3
            ])->select()->toArray();

            $buyerUserModel
                ->where([
                    'level' => 3,
                    'pid' => ['in', $check_ids]
                ])->delete();

            $ids = explode(',', $ids);
            $check_ids = explode(',', $check_ids);

            $data = [];
            foreach ($ids as $id) {
                foreach ($check_ids as $check_id) {
                    $data[] = [
                        'pid' => $check_id,
                        'uid' => $id,
                        'level' => 3
                    ];
                }
            }
            $buyerUserModel->allowField(true)->saveAll($data);
            $this->success('设置成功');
        } else {
            $userModel = new UserModel();

            $where = [];
            $uid = cmf_get_current_admin_id();
            $flag = false;
            if ($uid != 1) {
                $roles = db('role_user')
                    ->where(['user_id' => $uid])
                    ->column('role_id');

                $role_deps = get_role_department($roles, 'data_to_all_user');
                foreach ($role_deps as $role_dep) {
                    if ($role_dep['data_to_all_user']) {
                        $flag = true;
                    }
                }
            }

            if ($uid != 1 && !$flag) {
                $where['dep.id'] = ['in', getUsersGroup($uid)];
            }
            $where['user_status'] = ['neq', 0];

            $lists = $userModel
                ->alias('user')
                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
                ->field([
                    'user.*',
                    'dep.name as dep_name,dep.id as dep_id'
                ])->where($where)->select();

            $users = $buyerUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 3
            ])->column('uid');

            $this->assign('lists', $lists);
            $this->assign('users', $users);
            return $this->fetch();
        }
    }

    public function lock()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误！');
        }
        $buyerModel = new RongcuiBuyerModel();
        $item = $buyerModel->find($id);
        if ($item['lock_uid']) {
            $this->error('改数据已被锁定！');
        }
        $count = $buyerModel->where([
            'lock_uid' => cmf_get_current_admin_id(),
            'data_type' => 0,
        ])->field('count(id) as count')->find();

        if ($count['count'] < 200) {
            $result = $buyerModel->save([
                'lock_uid' => cmf_get_current_admin_id(),
                'lock_time' => time()
            ], ['id' => $id, 'lock_uid' => 0]);
            if ($result) {
                $this->success('锁定成功');
            } else {
                $this->error('改数据已被锁定！');
            }
        } else {
            $this->error('已锁定200条数据！');
        }
    }

    public function unlock()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误！');
        }
        $buyerModel = new RongcuiBuyerModel();
        $item = $buyerModel->find($id);
        if (!$item['lock_uid']) {
            $this->error('该数据已被解锁！');
        }
        if ($item['unlock']) {
            $this->error('解锁中！');
        }
        $result = $buyerModel->save([
            'unlock' => 1,
        ], ['id' => $id,'unlock' => 0]);
        if ($result) {
            $this->success('解锁申请成功！');
        } else {
            $this->error('解锁申请失败！');
        }
    }

    public function tolock()
    {
        $id = $this->request->param('id', 0, 'intval');
        $ids = $this->request->param('ids/a', []);
        if (!$id && !$ids) {
            $this->error('非法访问');
        }
        $ids[] = $id;
        $buyerModel = new RongcuiBuyerModel();
        $result = $buyerModel->save([
            'unlock' => 0,
            'lock_uid' => 0,
            'lock_time' => 0,
            'data_type' => 0,
            'is_done' => 0,
        ], ['id' => ['in',$ids]]);
        if ($result) {
            $this->success('解锁成功！');
        } else {
            $this->error('解锁失败！');
        }
    }

    public function unlock_se()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误！');
        }
        $buyerModel = new RongcuiBuyerModel();
        $item = $buyerModel->find($id);
        if (!$item['unlock']) {
            $this->error('该数据已被解锁！');
        }
        $result = $buyerModel->save([
            'unlock' => 0,
            'lock_uid' => 0,
            'lock_time' => 0,
            'data_type' => 0,
            'is_done' => 0,
        ], ['id' => $id,'unlock' => 1]);
        if ($result) {
            $this->success('解锁成功！');
        } else {
            $this->error('解锁失败！');
        }
    }

    public function lock_lists()
    {
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['lock_uid'] = ['in', $users];
        }else{
            $where['lock_uid'] = ['neq', 0];
        }

        if(input('category')) {
            $where['ctype.cate_id'] = input('category');
        }
        if (input('source')) {
            $where['buyer.source'] = input('source');
        }
        if (input('nature')) {
            $where['buyer.nature'] = input('nature');
        }
        if (input('is_done')) {
            $where['buyer.is_done'] = input('is_done', 0, 'intval') - 1;
        }
        if (input('start_time')) {
            $where['buyer.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d', $endtime));
            if ($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['buyer.createtime'])) {
                $where['buyer.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['buyer.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['buyer.name|buyer.phone|buyer.remark|user.user_nickname|userb.user_nickname'] = ['like', "%$keyword%"];
        }
        if (input('day')) {
            $day = input('day', 0, 'intval');
            if ($day) {
                $time = strtotime("-{$day} day");
                $where['newtime'] = ['lt', $time];
            }
//            $where['company|corporation|address|email|phone|remark|scope'] = ['like', "%$keyword%"];
        }
        $where['done_sq'] = ['neq',1];

        $buyerModel = new RongcuiBuyerModel();
        $lists = $buyerModel
            ->alias('buyer')
            ->join('__RONGCUI_INDUSTRY_TYPE__ ctype', 'buyer.id = ctype.pid')
            ->join('__USER__ user', 'buyer.lock_uid = user.id')
            ->join('__RONGCUI_BUYER_USER__ buyer_user', 'buyer.id = buyer_user.pid and buyer_user.level = 1')
            ->join('__CUSTOMER_NATURE__ nature', 'buyer.nature = nature.id','left')
            ->join('__RONGCUI_BUYER_USER__ buser','buyer.id = buser.pid and buser.level = 1')
            ->join('__USER__ userb','userb.id = buser.uid')
            ->group('buyer.id')
            ->where($where)
            ->field([
                'buyer.*',
                'user.user_nickname',
                'userb.user_nickname bname',
                'nature.name as nname',
                'buyer_user.uid as cuid',
            ])
            ->order('buyer.lock_time desc,buyer.createtime desc,buyer.id desc')
            ->paginate();

        $industryCateModel = new RongcuiIndustryCateModel();
        $cate = $industryCateModel->where([
            'status' => 1,
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $customerNatureModel = new CustomerNatureModel();
        $source = $customerNatureModel->where([
            'type' => 2,
            'is_del' => 0
        ])->field('id,name')->select();

        $nature = $customerNatureModel->where([
            'type' => 8,
            'is_del' => 0
        ])->field('id,name')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('source', $source);
        $this->assign('nature', $nature);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);
        $this->assign('uid', $uid);
        return $this->fetch();
    }

    function unlock_lists() {

        $where = [
            'unlock' => 1
        ];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['lock_uid'] = ['in', $users];
        }else{
            $where['lock_uid'] = ['neq', 0];
        }
        if(input('category')) {
            $where['ctype.cate_id'] = input('category');
        }
        if (input('source')) {
            $where['buyer.source'] = input('source');
        }
        if (input('is_done')) {
            $where['buyer.is_done'] = input('is_done', 0, 'intval') - 1;
        }
        if (input('start_time')) {
            $where['buyer.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d', $endtime));
            if ($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['buyer.createtime'])) {
                $where['buyer.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['buyer.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['buyer.name|buyer.phone|buyer.remark'] = ['like', "%$keyword%"];
        }

        $buyerModel = new RongcuiBuyerModel();
        $lists = $buyerModel
            ->alias('buyer')
            ->join('__RONGCUI_INDUSTRY_TYPE__ ctype', 'buyer.id = ctype.pid')
            ->join('__USER__ user', 'buyer.lock_uid = user.id')
            ->group('buyer.id')
            ->where($where)
            ->field([
                'buyer.*',
                'user.user_nickname',
            ])
            ->order('buyer.createtime desc,buyer.id desc')
            ->paginate();

        $industryCateModel = new RongcuiIndustryCateModel();
        $cate = $industryCateModel->where([
            'status' => 1,
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $customerNatureModel = new CustomerNatureModel();
        $source = $customerNatureModel->where([
            'type' => 2,
            'is_del' => 0
        ])->field('id,name')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('source', $source);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    public function done_sq() {
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['lock_uid'] = ['in', $users];
        }else{
            $where['lock_uid'] = ['neq', 0];
        }
        if(input('category')) {
            $where['ctype.cate_id'] = input('category');
        }
        if (input('source')) {
            $where['buyer.source'] = input('source');
        }
        if (input('is_done')) {
            $where['buyer.is_done'] = input('is_done', 0, 'intval') - 1;
        }
        if (input('start_time')) {
            $where['buyer.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d', $endtime));
            if ($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['buyer.createtime'])) {
                $where['buyer.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['buyer.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['buyer.name|buyer.phone|buyer.remark'] = ['like', "%$keyword%"];
        }
        if (input('day')) {
            $day = input('day', 0, 'intval');
            if ($day) {
                $time = strtotime("-{$day} day");
                $where['newtime'] = ['lt', $time];
            }
//            $where['company|corporation|address|email|phone|remark|scope'] = ['like', "%$keyword%"];
        }
        $where['done_sq'] = 1;

        $buyerModel = new RongcuiBuyerModel();
        $lists = $buyerModel
            ->alias('buyer')
            ->join('__RONGCUI_INDUSTRY_TYPE__ ctype', 'buyer.id = ctype.pid')
            ->join('__USER__ user', 'buyer.lock_uid = user.id')
            ->group('buyer.id')
            ->where($where)
            ->field([
                'buyer.*',
                'user.user_nickname',
            ])
            ->order('buyer.createtime desc,buyer.id desc')
            ->paginate();

        $industryCateModel = new RongcuiIndustryCateModel();
        $cate = $industryCateModel->where([
            'status' => 1,
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $customerNatureModel = new CustomerNatureModel();
        $source = $customerNatureModel->where([
            'type' => 2,
            'is_del' => 0
        ])->field('id,name')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('source', $source);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    function done_cl() {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误');
        }

        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['lock_uid'] = ['in', $users];
        }
        $where['buyer.id'] = $id;

        $buyerModel = new RongcuiBuyerModel();
        $buyer = $buyerModel
            ->alias('buyer')
            ->where($where)
            ->field([
                'buyer.id',
            ])
            ->find();
        if (!$buyer) {
            $this->error('非法操作');
        }
        $type = $this->request->param('type', 0, 'intval');

        if($type) {
            $buyerModel->save([
                'is_done' => 1,
                'done_time' => 0,
                'done_sq' => 0
            ], ['id' => $id]);
            $this->success('处理完成');
        }else{
            $buyerModel->save([
                'done_sq' => 2,
                'done_time' => time(),
            ], ['id' => $id]);
            $this->success('处理完成');
        }
    }

    function buyer_select()
    {
        $rongcuiBuyerModel = new RongcuiBuyerModel();

        $where = [
            'done_sq' => ['neq', 1],
            'lock_uid' => cmf_get_current_admin_id(),
            'abutment' => 0
        ];

        $lists = $rongcuiBuyerModel
            ->where($where)
            ->select();

        $this->assign('lists', $lists);
        return $this->fetch();
    }
}